<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Admin_CourseController extends Zend_Controller_Action
{

    private $_courseService;
    private $_memberService;

    public function init()
    {
        $this->_courseService = $this->_helper->getService('Core_Service_Course');
        $this->_memberService = $this->_helper->getService('Core_Service_Member');
    }

    public function indexAction()
    {
        $this->view->courses = $this->_courseService->fetchAllCourses(false);
        $this->view->competences = $this->_courseService->fetchAllCompetences(false);
    }

    public function createAction()
    {
        $this->_helper->acl()->isAllowed('service:course', 'create');
        $form = new Admin_Form_Course_Basic();
        $request = $this->getRequest();

        if ($request->isPost() && $form->isValid($request->getPost()))
        {
            $result = $this->_courseService->create($form->getValues());
            if ($result) {
                $this->view->flashMessage()->addMessage('La til et nytt kurs', RedCross_View_Helper_FlashMessage::SUCCESS);
                return $this->_helper->redirector('index');
            } else {
                $this->view->unknownError = true;
            }
        }
        $this->view->form = $form;
    }

    public function editAction()
    {
        $this->_helper->acl()->isAllowed('service:course', 'edit');

        $course_id = $this->_getParam('id');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($course_id)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $course_id = (int)$course_id;

        $course = $this->_courseService->fetch($course_id);
        $editForm = new Admin_Form_Course_Edit();
        $editForm->fillForm($course);

        $request = $this->getRequest();
        if ($request->isPost())
        {
            $values = $request->getPost();

            // Editing course information
            if ($values['action'] === Admin_Form_Course_Edit::ACTION && $editForm->isValid($values))
            {
                $result = $this->_courseService->edit($course_id, $editForm->getValues());
                if ($result === true) {
                    $this->view->flashMessage()->addMessage('Kurs oppdatert', RedCross_View_Helper_FlashMessage::SUCCESS);
                    return $this->_helper->redirector('index');
                } else {
                    $this->view->unknownError = true;
                }
            }
        }

        $this->view->course = $course;
        $this->view->editForm = $editForm;

        if($course->type === "course"){
            $courseOrCompetence = "kurset";
        } elseif ($course->type === "competence") {
            $courseOrCompetence = "kompetansen";
        }

        /* Populate list of members */
        $filterContent = array(
            'has_course' => 'Medlemmer som har ' . $courseOrCompetence,
            'not_course' => 'Medlemmer som ikke har ' . $courseOrCompetence,
            'all'        => 'Alle medlemmer',
        );        
        $filterForm = $this->view->filterForm = $this->view->filterForm($filterContent);
        $filterForm->setAction($this->view->url(array('module' => 'admin', 'controller' => 'course', 'action' => 'edit'), null, false));

        if ($request->isGet() && $this->_getParam('filter', false) && $filterForm->isValid($request->getQuery())) {
            $value = $filterForm->getValue('filter');
            switch ($value) {
            case 'has_course':
                $this->view->members = $this->_memberService->fetchMembersWithCourse($course_id);
                break;
            case 'not_course':
                $this->view->members = $this->membersWithoutCourse($course_id);
                break;
            case 'all':
                $this->view->members = $this->_memberService->fetchAllActive();
            }
        }

        if (!isset($this->view->members)) {
            $this->view->members = $this->_memberService->fetchMembersWithCourse($course_id);
        }
    }
    /*
     * Helper method for aggregating members that does not have a
     * given expertise. Doctrine did not like the one query approach.
     */
    private function membersWithoutCourse($course_id){
        $hasCourse = $this->_memberService->fetchMembersWithCourse($course_id)->getData();
        $allMembers= $this->_memberService->fetchAllActive()->getData();
        return array_diff($allMembers, $hasCourse);
    }

    public function addMembersAction() {
        $this->_helper->acl()->isAllowed('service:member', 'editCourses');

        $course_id = $this->_getParam('id');
        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($course_id)) {
            throw new RedCross_Exception_ValidationFailed();
        }

        $course_id = (int)$course_id;
        $course = $this->_courseService->fetch($course_id);

        if($course->type === "course"){
            $courseOrCompetence = "kurset";
        } elseif ($course->type === "competence") {
            $courseOrCompetence = "kompetansen";
        }


        $request = $this->getRequest();
        if ($request->isPost())
        {
            $values = $request->getPost();

            // Adding members to course
            // TODO: Move action value to constant
            if (isset($values['add_members_to_course']))
            {
                foreach ($values['members'] as $memberId) {
                    if (!$validator->isValid($memberId)) {
                        throw new RedCross_Exception_ValidationFailed();
                    }
                    $memberId = (int)$memberId;
                    $member = $this->_memberService->fetchById($memberId);
                    $course_date = '';
                    if (isset($values['course_date']))
                    {
                        $course_date = $values['course_date'];
                    }

                    $competence_date = '';
                    if (isset($values['competence_date']))
                    {
                        $competence_date = $values['competence_date'];
                    }

                    $courseAdded = $this->_memberService->addCourse($memberId, array('course' => $course_id, 'course_date' => $course_date,'competence_date' => $competence_date));

                    if (is_object($courseAdded)) {
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble tildelt ' . $courseOrCompetence  . '.', RedCross_View_Helper_FlashMessage::SUCCESS);
                    } else {
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble ikke tildelt ' . $courseOrCompetence . '.' , RedCross_View_Helper_FlashMessage::ERROR);
                    }
                }
            }
            elseif (isset($values['remove_members_from_course']))
            {
                foreach ($values['members'] as $memberId) {
                    if (!$validator->isValid($memberId)){
                        throw new RedCross_Exception_ValidationFailed();
                    }
                    $memberId = (int) $memberId;
                    $member = $this->_memberService->fetchById($memberId);
                    $courseRemoved = $this->_memberService->removeCourse($memberId, $course_id);

                    if ($courseRemoved) {
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble fratatt ' . $courseOrCompetence . '.', RedCross_View_Helper_FlashMessage::SUCCESS);
                    } else {
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble ikke fratatt ' . $courseOrCompetence . '.', RedCross_View_Helper_FlashMessage::ERROR);
                    }
                }
            }
        }
        
        return $this->_helper->redirector('edit', null, null, array('id' => $course_id));
    }
}
